﻿using AutoMapper;
using MediatR;
using StoreIModels;
using StoreISet.Applicationes.Command;
using StoreRepositorys.Interface;

namespace StoreISet.Applicationes.CommandHandler
{
    public class StoreCreateCommandHandler : IRequestHandler<StoreCreateCommand, int>
    {
        public IStoreRepository _IRepository;
        public IRelationshipStoreRepository _IRelationshipStoreRepository;
        public IMapper _mapper;
        public StoreCreateCommandHandler (IStoreRepository storeRepository,IMapper mapper, IRelationshipStoreRepository relationshipStoreRepository)
        {
            _IRepository= storeRepository;
            _mapper= mapper;
            _IRelationshipStoreRepository= relationshipStoreRepository;
        }
        public  async Task<int> Handle(StoreCreateCommand request, CancellationToken cancellationToken)
        {
            try
            {

                StoreModel models = _mapper.Map<StoreModel>(request);
            
                var res = await _IRepository.Addasync(models);
              
                var list=await _IRepository.GetAllAsync(x=>x.StoreName==request.StoreName&&x.BranchStoreName==request.BranchStoreName);
                
                var tolist = request.adderId.Split(',');
                var Restult = 0;
                RelationshipStoreModels Remodels = new RelationshipStoreModels();
                foreach (var item in tolist)
                {
                  
                    Remodels.StoreId = list.FirstOrDefault().StoreId;  
                    Remodels.AssortedId = Convert.ToInt32(item);
                    Restult = await _IRelationshipStoreRepository.Addasync(Remodels);
                }
                return res;
            }
            catch (Exception)
            {

                throw;
            }
        }
    }
}
